<template>
  <XenPageLayout
    title="新增入职申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="填写入职申请信息"
        subtitle="请填写完整入职申请信息以便审批"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @attachmentUpload="handleAttachmentUpload"
        @attachmentDelete="handleAttachmentDelete"
        @attachmentPreview="handleAttachmentPreview"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      />
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useOnboardingInfo } from "./composables/useInfo";
// 导入统一事件系统
import { OnboardingInfoEvents } from "@/utils/eventBus";
// 导入文件上传工具
import { uploadImage } from "@/utils/unirequest";

// 强制更新触发器
const forceUpdateTrigger = ref(0);

// 获取新增页面的表单分组（动态计算禁用状态和选项）
const formSections = computed(() => {
  // 依赖强制更新触发器，确保响应式更新
  forceUpdateTrigger.value;

  console.log("重新计算表单配置");
  const sections = getFormSectionsByPageType("create");

  // 动态设置岗位字段的禁用状态和选项数据
  sections.forEach((section) => {
    section.fields.forEach((field) => {
      if (field.key === "jobPositionId") {
        field.disabled = isPositionFieldDisabled("jobPositionId");
        field.options = getPositionOptionsText("jobPositionId");
        field.optionsData = getPositionOptions("jobPositionId");
        console.log("工作岗位字段配置:", {
          disabled: field.disabled,
          optionsCount: field.options?.length || 0,
        });
      }
    });
  });

  return sections;
});

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "cancel",
    label: "取消",
    type: "default" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用入职申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  createOnboarding,
  search,
  getBillCode,
  // 部门岗位联动相关方法
  handleDepartmentChange,
  isPositionFieldDisabled,
  getPositionOptions,
  getPositionOptionsText,
} = useOnboardingInfo();

// 监听岗位选项变化，强制重新计算表单配置
watch(
  () => [getPositionOptions("jobPositionId").length, formData.groupId],
  () => {
    console.log("岗位选项或部门发生变化，强制更新表单");
    forceUpdateTrigger.value++;
  },
  { deep: true },
);

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = async (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  // XenDynamicFormCard组件会同时触发 @update:model-value 和 @change 事件
  // @update:model-value 已经通过 handleFormDataChange 设置了 formData[fieldKey] = value (部门ID)
  // 这里我们只需要保存部门ID到pickerValues中，用于提交到后端

  // 确保formData中存储的是部门ID（用于组件正确显示选中状态）
  formData[fieldKey] = value;

  // 同时保存到pickerValues中（用于提交到后端）
  pickerValues[fieldKey] = value;

  // 处理部门变化时的岗位联动逻辑
  await handleDepartmentChange(fieldKey, value);

  // 触发验证
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  // 对于自动补全，formData中存储显示文本，pickerValues中存储实际值
  if (option) {
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";
  }

  // 触发验证
  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  // 搜索逻辑已经在组件内部通过searchApi处理
  console.log("搜索:", fieldKey, query);
};

// 获取文件URL
const getFileUrl = (fileId: string | null) => {
  if (!fileId) return "";
  return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
};

// 页面加载时获取数据
onMounted(async () => {
  // 初始化选项数据
  await initializeOptions();

  // 获取单据编号
  const billCode = await getBillCode();
  if (billCode) {
    formData.billCode = billCode;
  }
});

// 图片上传处理（单文件上传）
const handleImageUpload = async (field: any, event: any) => {
  console.log("图片上传:", field.key, event);
  const files = event.tempFiles || [];

  if (files.length > 0) {
    // 由于是单文件上传，如果上传多个文件则只取第一个
    const file = files[0];

    uni.showLoading({ title: "上传中..." });

    const filePath = file?.path || file?.tempFilePath;
    if (filePath) {
      const fileId = await uploadImage(filePath, "image");
      console.log(`${field.key}上传成功，文件ID:`, fileId);

      const fileName = file?.name || file?.fileName || "图片";
      const fileInfo = {
        name: fileName,
        url: getFileUrl(fileId),
        extname: file?.extname || "jpg",
        size: file?.size || 0,
        fileID: fileId, // 文件ID用于后端提交
      };

      // 存储为数组格式供UI组件显示（单文件上传包装成数组）
      formData[field.key] = [fileInfo];

      uni.hideLoading();
      uni.showToast({
        title: "图片上传成功",
        icon: "success",
      });
    }
  }
};

const handleImageSuccess = (_field: any, _event: any) => {
  // 图片上传成功回调（由于已在handleImageUpload中处理，这里可以为空或进行额外处理）
  console.log("图片上传成功回调:", _field?.key, _event);
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败回调
  console.log("图片上传失败回调:", _field?.key, _event);
  uni.showToast({
    title: "图片上传失败，请重试",
    icon: "none",
  });
};

const handleImageDelete = (field: any, event: any) => {
  console.log("图片删除:", field.key, event);
  // 单文件删除，设置为空数组
  formData[field.key] = [];
  uni.showToast({
    title: "图片已删除",
    icon: "success",
  });
};

// 文件上传处理（单文件上传）
const handleFileUpload = async (field: any, event: any) => {
  console.log("文件上传:", field.key, event);
  const files = event.tempFiles || [];

  if (files.length > 0) {
    // 由于是单文件上传，如果上传多个文件则只取第一个
    const file = files[0];

    uni.showLoading({ title: "上传中..." });

    const filePath = file?.path || file?.tempFilePath;
    if (filePath) {
      const fileId = await uploadImage(filePath, "file");
      console.log(`${field.key}上传成功，文件ID:`, fileId);

      const fileName = file?.name || file?.fileName || "文件";
      const fileInfo = {
        name: fileName,
        url: getFileUrl(fileId),
        extname: file?.extname || "pdf",
        size: file?.size || 0,
        fileID: fileId, // 文件ID用于后端提交
      };

      // 存储为数组格式供UI组件显示（单文件上传包装成数组）
      formData[field.key] = [fileInfo];

      uni.hideLoading();
      uni.showToast({
        title: "文件上传成功",
        icon: "success",
      });
    }
  }
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功回调（由于已在handleFileUpload中处理，这里可以为空或进行额外处理）
  console.log("文件上传成功回调:", _field?.key, _event);
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败回调
  console.log("文件上传失败回调:", _field?.key, _event);
  uni.showToast({
    title: "文件上传失败，请重试",
    icon: "none",
  });
};

const handleFileDelete = (field: any, event: any) => {
  console.log("文件删除:", field.key, event);
  // 单文件删除，设置为空数组
  formData[field.key] = [];
  uni.showToast({
    title: "文件已删除",
    icon: "success",
  });
};

// 附件上传处理（单文件上传）
const handleAttachmentUpload = async (field: any, files: any[]) => {
  console.log("附件上传:", field.key, files);

  if (files.length === 0) return;

  // 单文件上传限制
  if (files.length > 1) {
    uni.showToast({
      title: "仅支持上传1个文件",
      icon: "none",
      duration: 3000,
    });
    return;
  }

  uni.showLoading({ title: "上传中..." });

  try {
    const file = files[0];
    const filePath = file?.path || file?.tempFilePath;

    if (filePath) {
      const fileId = await uploadImage(filePath, "file");
      console.log(`${field.key}上传成功，文件ID:`, fileId);

      const fileName = file?.name || file?.fileName || "文件";
      const attachmentInfo = {
        name: fileName,
        url: getFileUrl(fileId),
        extname: file?.extname || "pdf",
        size: file?.size || 0,
        fileID: fileId, // 文件ID用于后端提交
        id: fileId,
      };

      // 单文件上传，直接替换现有文件
      formData[field.key] = [attachmentInfo];

      uni.hideLoading();
      uni.showToast({
        title: "简历上传成功",
        icon: "success",
      });
    }
  } catch (error) {
    console.error("文件上传失败:", error);
    uni.hideLoading();
    uni.showToast({
      title: "文件上传失败，请重试",
      icon: "none",
    });
  }
};

// 附件删除处理
const handleAttachmentDelete = (field: any, attachment: any, index: number) => {
  console.log("附件删除:", field.key, attachment, index);
  // 单文件删除，设置为空数组
  formData[field.key] = [];
  uni.showToast({
    title: "简历已删除",
    icon: "success",
  });
};

// 附件预览处理
const handleAttachmentPreview = (field: any, attachment: any) => {
  console.log("附件预览:", field.key, attachment);
  // 附件组件内部已经处理了预览逻辑，这里可以做额外的处理
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "cancel":
      handleCancel();
      break;
    case "submit":
      handleSubmit();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 取消按钮
const handleCancel = () => {
  uni.navigateBack();
};

// 提交表单
const handleSubmit = async () => {
  uni.showLoading({ title: "提交中..." });

  // 使用Composable中的创建方法（两步提交流程）
  const response = await createOnboarding();

  uni.hideLoading();

  if (response.success && response.data && response.data.ID) {
    // 重新调用search接口获取最新的完整列表数据
    try {
      const searchResponse = await search({});
      if (searchResponse && searchResponse.length > 0) {
        // 发送完整列表数据更新事件
        OnboardingInfoEvents.emit("refresh", {
          id: response.data.ID,
          data: searchResponse,
          customAction: "add",
        });
      }
    } catch (error) {
      // 如果获取失败，仍然发送简单的刷新事件作为备用方案
      OnboardingInfoEvents.emit("refresh", {
        id: response.data.ID,
        customAction: "add",
      });
    }

    uni.showToast({
      title: "提交成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } else {
    // 处理不同类型的错误信息
    let errorMessage = "提交失败，请重试";

    if (response.error) {
      // 显示具体的业务错误信息
      errorMessage = response.error;
    } else if (response.validation?.firstErrorMessage) {
      // 显示表单验证错误信息
      errorMessage = response.validation.firstErrorMessage;
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000, // 延长显示时间，让用户能看清错误信息
    });
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
</style>
